package com.equinox.spring_sse.controller;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import lombok.extern.slf4j.Slf4j;

/**
 * 10分钟 ，20分钟
 * 
 * @author Thinker
 *
 */
@RestController
@Slf4j
@CrossOrigin
public class SseEmitterController {
	@Value("${sse.timeout}")
	private String timeout;
	// 用于保存每个请求对应的 SseEmitter
	private Map<String, Result> sseEmitterMap = new ConcurrentHashMap<>();

	/**
	 * 返回SseEmitter对象
	 *
	 * @param clientId
	 * @return
	 */
	@RequestMapping("/start")
	public SseEmitter testSseEmitter(String clientId) {
		System.out.println(clientId);
		// 默认30秒超时,设置为0L则永不超时
		SseEmitter sseEmitter = new SseEmitter(0L);
		sseEmitterMap.put(clientId, new Result(clientId, System.currentTimeMillis(), sseEmitter));
		return sseEmitter;

	}

	// 这里使用输出的媒体类型为text/event-stream，这是服务端的SSE的支持
	@RequestMapping(value = "/send")
	public String push(String clientId) {
		try {
			Result result = sseEmitterMap.get(clientId);
			if (result != null && result.sseEmitter != null) {
				long timestamp = System.currentTimeMillis();
				result.sseEmitter.send(timestamp);
			}
		} catch (Exception e) {
			log.error("IOException!{}", e);
			return "error";
		}
		return "Succeed";
	}

	/**
	 * 将SseEmitter对象设置成完成
	 *
	 * @param clientId
	 * @return
	 */
	@RequestMapping("/end")
	public String completeSseEmitter(String clientId) {
		Result result = sseEmitterMap.get(clientId);
		if (result != null) {
			sseEmitterMap.remove(clientId);
			result.sseEmitter.complete();
		}
		return "Succeed!";
	}

}
